import { useState, useEffect, useCallback, lazy, Fragment } from 'react'
import { useNavigate } from 'react-router-dom'
/* -------------------------------------------------------- Sync Function -- */
import ControlsUtils from '#cpt/utils/controls'
/* -------------------------------------------------------- Declare -- */
const { $lazy, $fn, $, $config } = window
/* -------------------------------------------------------- Async Component -- */
const Button = lazy(()=>import('@antd/button'))
const Dropdown = lazy(()=>import('@antd/dropdown'))
const Popconfirm = lazy(()=>import('@antd/popconfirm'))
const Space = lazy(()=>import('@tp/space'))
const Upload = $lazy.hook(()=>import('@antd/form/upload'))
/* -------------------------------------------------------- 按钮组配置 -- */
const Index = props => {
	let { data, className, style, size='small', align='end', loading, refresh, back, table, isTable, keys, rows, global, perm } = props
	
	const [result, setResult] = useState(data)
	
	const navigate = useNavigate()
	
	useEffect(()=>setResult( data ), [data]) // eslint-disable-line
	
	useEffect(()=>{
		setResult( data => {
			if( refresh ){ data = [...data, { mode:'refresh' } ] } 	// 刷新
			if( back ){ data = [...data, { mode:'back' } ] }		// 返回
			return data
		})
	}, [ ])  // eslint-disable-line
	
	const onClick = option => ControlsUtils({ option, navigate, tableConfig: table, global })
	const setDisabled = useCallback(({ mode, disabled, isKeys, name, exc }) => {
		if( $fn.getResult(props.disabled) ){
			return true
		}else{
			if( ['del','delPop'].includes(mode) && !isTable ){ isKeys = 1 }
			if( $fn.hasObject(table) && isKeys && table?.row ){
				const { tableRef } = table
				if( tableRef ){
					if( keys?.length === 0 ){
						return true
					}else{
						let ref = tableRef()
						if( name ){
							if(table?.row?.type === 1){
								if( exc ){
									return rows?.[name]
								}else{
									return !rows?.[name]
								}
							}else{
								if( exc ){
									return rows?.[rows.length-1]?.[name]
								}else{
									return !rows?.[rows.length-1]?.[name]
								}
							}
						}
						return $fn.getResult(disabled, { keys, rows:ref?.rows } )
					}
				}
			}else{
				return $fn.getResult(disabled)
			}
		}
	}, [keys, rows])  // eslint-disable-line
	
	const Component = $fn.hasArray(result) ? result.map(( v, i ) => {
		if( !$fn.hasObject( v )) return null
		let { hide, mode, label, ghost, show } = v
		v.label = label ? label : $config.btnName[mode]
		if( isTable ){
			v.ghost = ghost ?? true
		}else{
			v.ghost = $fn.isBoolean( ghost ) ? ghost : (['del', 'delPop', 'back', 'refresh', 'clear'].includes(mode) ? true : ghost)
		}
		
		const disabled = setDisabled(v)
		if( Array.isArray(perm) && $fn.getUser().role !== 0 ){
			if( ['del', 'delPop'].includes(mode) && !perm.includes('d') ) return null
			else if( mode==='mod' && !perm.includes('u') ) return null
			else if( mode==='add' && !perm.includes('c') ) return null
			else if( ['upload', 'confirm', 'formModal','submit', 'mg_download', 'download'].includes(mode) && !perm.includes('o') ) return
			else {
				if( v.perm && v.perm !== 'a' && !perm.includes(v.perm) ) return null
			}
		}
		
		// hide = $fn.getResult(hide)
		// show = $fn.getResult(show)
		
		if( hide ) return null
		if( show === false || show === 0 ){ return null }
		
		if( mode === 'delPop' ){
			const title = v.msg ?? `确认${v.label}此数据？`
			return (
				<Popconfirm key={i} title={ title } onConfirm={ onClick.bind(null,v) }>
					<div><Button size={size} loading={loading} {...v} disabled={disabled} stop={false}/></div>
				</Popconfirm>
			)
		}else if( mode === 'dropdown' || mode === 'dropdown-pop'){
			return <Dropdown size={size} loading={loading} {...v} disabled={disabled}  key={i} onClick={m => {
				onClick(m)
				v?.change?.(m, v)
			}}/>
		}else if( mode === 'upload' && v.api){
			return <Upload listType='button' showUploadList={false} loading={loading} {...v}  key={i}/>
		}else if( mode === 'div' ){
			return <div {...v} key={i}>{$.cpt(v.slot)}</div>
		}else if( mode === 'ex' ){
			return <div className='ex' {...v} key={i}>{$.cpt(v.slot)}</div>
		}else{
			if( v.slot ){
				return <Fragment key={i}>{$.cpt(v.slot)}</Fragment>
			}
			return <Button size={size} loading={loading} {...v} disabled={disabled} key={i} onClick={onClick.bind(null,v)}/>
		}
	}) : null
	const cpt = $fn.hasArray(Component) ? Component.filter(v => !!v) : null
	
	return $fn.hasArray( result ) && $fn.hasArray( cpt ) ? (
			<Space align={align} className={className} style={style}>
				{ Component }
			</Space>
	) : null
}
export default Index